﻿using LayuiMvc.DataEntity;
using LayuiMvc.DataEntity.IdentityEntity;
using LayuiMvc.DataModel.Identity;
using LayuiMvcUtil.Result;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace LayuiMvc.Logic.Identity
{
    public class IdentityClaimManager
    {
        #region 声明列表
        /// <summary>
        /// 获取声明列表
        /// </summary>
        /// <param name="userId">用户Id</param>
        /// <param name="userManager">用户管理器</param>
        /// <returns></returns>
        public async Task<DataResult<List<ClaimModel>>> ClaimListAsync(int userId,IdentityUserManager userManager)
        {
            DataResult<List<ClaimModel>> rtnResult = new DataResult<List<ClaimModel>>();

            //获取用户声明数据
            IList<Claim> userClaimList = await userManager.GetClaimsAsync(userId);
            List<string> userClaimValueList = userClaimList.Select(m => m.Value).ToList();

            using(EFContext db = new EFContext())
            {
                List<ClaimModel> claimList = await db.IdentityClaim.Select(m => new ClaimModel()
                {
                    ClaimId = m.ClaimId,
                    ClaimType = m.ClaimType,
                    ClaimValue = m.ClaimValue,
                    ClaimDescription = m.ClaimDescription,
                    IsHasClaim = userClaimValueList.Any(s => s == m.ClaimValue)
                }).ToListAsync();

                rtnResult.data = claimList;
            }
            return rtnResult;
        }
        #endregion

        #region 根据Id数组获取声明列表
        
        /// <summary>
        /// 根据声明Id数组获取声明列表
        /// </summary>
        /// <param name="claimIdList"></param>
        /// <returns></returns>
        public async Task<List<Claim>> GetClaimsListByIdAsync(int[] claimIdList)
        {
            using(EFContext db = new EFContext())
            {
                List<Claim> claimList = new List<Claim>();
                foreach (int claimId in claimIdList)
                {
                    IdentityClaimEntity claimEntity = await db.IdentityClaim.FindAsync(claimId);

                    if (claimEntity!=null)
                    {
                        Claim claim = new Claim(claimEntity.ClaimType, claimEntity.ClaimValue);
                        claimList.Add(claim);
                    }
                }

                return claimList;
            }
        }

        #endregion
    }
}
